"""
和文件相关的类定义
"""
import json

from data_define import Record


class FileReader:
    def read_data(self) -> list[Record]:
        """
        将读到的每一条数据转换为Record对象
        :return: Record对象组成的列表
        """
        pass


class TextFileReader(FileReader):
    def __init__(self, path):
        """
        :param path: 记录文件路径
        """
        self.path = path

    def read_data(self) -> list[Record]:
        f = open(self.path, "r", encoding="UTF-8")
        record_list = []
        for line in f.readlines():
            line = line.strip()  # 去除末尾'\n'
            data_list = line.split(",")  # 分割数据为列表
            # 将列表内容存入Record对象
            record = Record(data_list[0], data_list[1], int(data_list[2]), data_list[3])
            # 将Record对象存储到列表
            record_list.append(record)
        f.close()
        return record_list


class JsonFileReader(FileReader):
    def __init__(self, path):
        self.path = path

    def read_data(self) -> list[Record]:
        f = open(self.path, "r", encoding="UTF-8")
        record_list = []
        for line in f.readlines():
            data_dict = json.loads(line)
            record = Record(data_dict['date'], data_dict['order_id'], int(data_dict['money']), data_dict['province'])
            record_list.append(record)
        f.close()
        return record_list


if __name__ == '__main__':
    text_file_reader = TextFileReader("D:/Code/KnowCode/my_python/资料/第13章资料/2011年1月销售数据.txt")
    list1 = text_file_reader.read_data()
    json_file_reader = JsonFileReader("D:/Code/KnowCode/my_python/资料/第13章资料/2011年2月销售数据JSON.txt")
    list2 = json_file_reader.read_data()
    for val in list1:
        print(val)

    for val in list2:
        print(val)
